﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using TBM.Filters;
using TBM.Attributes;
using System.Text;

namespace TBM.Controllers
{
    public partial class MailController : MasterController
    {
        [Description("邮件编辑")]
        [TBMAuthorize("邮件管理", "邮件编辑")]
        public ActionResult Editor()
        {
            long? mid = Core.ParamType.Long(Request["mid"]);
            string type = Request["type"] != null ? Request["type"].ToString() : null;

            ViewBag.MID = "";
            ViewBag.SendTo = "";

            Models.Mail mail = new Models.Mail();
            if (mid != null)
            {
                cmd.CommandText = "p_ReadMail";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Clear();
                cmd.Parameters.Add("@MID", SqlDbType.BigInt);
                cmd.Parameters.Add("@Type", SqlDbType.Int);
                cmd.Parameters.Add("@Own", SqlDbType.VarChar, 15);
                cmd.Parameters["@MID"].Value = mid;
                cmd.Parameters["@Type"].Value = 5;
                cmd.Parameters["@Own"].Value = CurrUser.UID;

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataSet ds = new DataSet();

                    da.Fill(ds);

                    DataTable dtMailContext = ds.Tables[0];
                    DataTable dtMailFrom = ds.Tables[1];
                    DataTable dtMailTo = ds.Tables[2];

                    if (dtMailContext.Rows.Count > 0)
                    {
                        DataRow row = dtMailContext.Rows[0];
                        mail.ID = (long)row["ID"];
                        mail.Subject = row["Subject"].ToString();
                        mail.Context = row["Context"].ToString();
                        mail.CreateDate = Convert.ToDateTime(row["CreateDate"]);

                        if (dtMailFrom.Rows.Count > 0)
                        {
                            DataRow r = dtMailFrom.Rows[0];
                            mail.MailFrom = new Models.UserListItem
                            {
                                UID = r["UID"].ToString(),
                                FullName = r["FullName"].ToString(),
                                PicUrl = r["PicUrl"] != DBNull.Value ? r["PicUrl"].ToString() + "small.png?" + DateTime.Now.Ticks : Core.Config.DefaultPic
                            };
                        }

                        mail.MailTo = new List<Models.UserListItem>();
                        foreach (DataRow mailto in dtMailTo.Rows)
                        {
                            mail.MailTo.Add(new Models.UserListItem
                            {
                                UID = mailto["UID"].ToString(),
                                FullName = mailto["FullName"].ToString(),
                                PicUrl = mailto["PicUrl"] != DBNull.Value ? mailto["PicUrl"].ToString() + "small.png?" + DateTime.Now.Ticks : Core.Config.DefaultPic
                            });
                        }
                        ViewBag.FindMail = true;
                        if (type != null)
                        {
                            StringBuilder context = new StringBuilder("<br /><br /><br />_____________________________________________");
                            context.AppendFormat(@"<p>
                                                        <label class=""bold"">来自：</label> 
                                                        <span class=""bold"">{0} </span><span>&lt;{1}&gt; </span>
                                                    </p>", mail.MailFrom.FullName, mail.MailFrom.UID);
                            context.AppendFormat(@"<p>
                                                        <label class=""bold"">日期：</label> {0}
                                                    </p>", mail.CreateDate.ToString("yyyy-MM-dd hh:mm:ss"));
                            context.Append("<label class=\"bold\">发至：");

                            int Count = mail.MailTo.Count;
                            for (int i = 0; i < Count; i++)
                            {
                                context.AppendFormat("<label>{0}</label>", mail.MailTo[i].FullName);

                                if (i < Count - 1)
                                {
                                    context.Append(",");
                                }
                            }

                            context.Append("</label> ");
                            context.AppendFormat("<p>{0}</p>", mail.Context);

                            mail.Context = context.ToString();

                            switch (type)
                            {
                                case "reply":
                                    mail.Subject = "RE: " + mail.Subject;
                                    ViewBag.SendTo = JsonConvert.SerializeObject(new List<Models.UserListItem> { mail.MailFrom });
                                    break;
                                case "forward":
                                    mail.Subject = "FW: " + mail.Subject;
                                    break;
                            }
                        }
                        else
                        {
                            ViewBag.SendTo = JsonConvert.SerializeObject(mail.MailTo);
                            ViewBag.MID = mid;
                        }
                    }
                    else
                    {
                        ViewBag.FindMail = false;
                    }
                }
            }

            ViewBag.Mail = mail;

            return PartialView();
        }


        /// <summary>
        /// 保存邮件至草稿箱
        /// </summary>
        /// <returns></returns>
        [ParentAction("Editor")]
        [Description("保存至草稿箱")]
        [TBMAuthorize("邮件管理", "保存至草稿箱")]
        [ValidateInput(false)]
        public JsonResult Save(long? mid, string[] touid, string subject, string context)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_SaveMail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();
            cmd.Parameters.Add("@MID", SqlDbType.BigInt);
            cmd.Parameters.Add("@Subject", SqlDbType.NVarChar, 200);
            cmd.Parameters.Add("@Context", SqlDbType.NText);
            cmd.Parameters.Add("@MailFrom", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@MailTo", SqlDbType.VarChar, 8000);
            cmd.Parameters.Add("@Return", SqlDbType.Int);

            cmd.Parameters["@MID"].Value = Core.CommandParamType.Long(mid);
            cmd.Parameters["@Subject"].Value = subject;
            cmd.Parameters["@Context"].Value = context;
            cmd.Parameters["@MailFrom"].Value = CurrUser.UID;
            cmd.Parameters["@MailTo"].Value = touid == null ? "" : String.Join(",", touid);
            cmd.Parameters["@Return"].Direction = ParameterDirection.ReturnValue;

            Core.LangItem li = cmd.ExecuteNonQuery() > 0 ? Core.Lang.SAVE_MAIL_TO_DRAFT_SUCCESS : Core.Lang.CMD_FAILED;

            result.Data = new Models.ExecuteResult
            {
                Result = li.Code == Core.Lang.SAVE_MAIL_TO_DRAFT_SUCCESS.Code,
                Code = li.Code,
                Message = li.Message,
                Data = new
                {
                    MID = cmd.Parameters["@Return"].Value
                }
            };

            return result;
        }


        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="mid"></param>
        /// <param name="subject"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        [ParentAction("Editor")]
        [Description("发送邮件")]
        [TBMAuthorize("邮件管理", "发送邮件")]
        [ValidateInput(false)]
        public JsonResult Send(long? mid, string subject, string context)
        {
            JsonResult result = new JsonResult();

            cmd.CommandText = "p_SendMail";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Clear();

            cmd.Parameters.Add("@MID", SqlDbType.BigInt);
            cmd.Parameters.Add("@Subject", SqlDbType.NVarChar, 200);
            cmd.Parameters.Add("@Context", SqlDbType.NText);
            cmd.Parameters.Add("@MailFrom", SqlDbType.VarChar, 15);
            cmd.Parameters.Add("@MailTo", SqlDbType.VarChar, 8000);
            cmd.Parameters.Add("@Return", SqlDbType.Int);

            cmd.Parameters["@MID"].Value = Core.CommandParamType.Long(mid);
            cmd.Parameters["@Subject"].Value = subject;
            cmd.Parameters["@Context"].Value = context;
            cmd.Parameters["@MailFrom"].Value = CurrUser.UID;
            cmd.Parameters["@MailTo"].Value = Core.CommandParamType.NullOrString(Request["touid"]);
            cmd.Parameters["@Return"].Direction = ParameterDirection.ReturnValue;

            cmd.ExecuteNonQuery();
            Core.LangItem li = null;
            Models.ExecuteResult er = new Models.ExecuteResult();
            er.Result = false;

            switch ((int)cmd.Parameters["@Return"].Value)
            {
                case 0:
                    // 执行成功
                    li = Core.Lang.CMD_SUCCESS;
                    er.Result = true;
                    break;
                case 1:
                    // 没有收件人地址
                    li = Core.Lang.EMAIL_NO_TO_ADDRESS;
                    break;
                case 2:
                    // 没有发件人地址
                    li = Core.Lang.EMAIL_NO_FROM_ADDRESS;
                    break;
                case 3:
                    // 邮件不能发给自己
                    li = Core.Lang.EMAIL_SEND_CANNOT_TO_SELF;
                    break;
            }

            er.Code = li.Code;
            er.Message = li.Message;

            result.Data = er;

            return result;
        }
    }
}
